package com.leo.ktvplayer.ui.playing;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 *
 */
public class TimeCounter extends Thread {

    /**
     * The counter interval time
     */
    private int intervalTime;
    /**
     * The counter summary time
     */
    private int sumTime;

    private OnTimerTickCallback onTimerTickCallback;

    private OnTimeFinishCallback onTimeFinishCallback;

    private boolean isrunning = true;

    private int coutingTime = 0;

    public TimeCounter(int intervalTime , int sumtTme){
        this.intervalTime = intervalTime;
        this.sumTime = sumtTme;

    }

    public void setOnTimerTickCallBack(OnTimerTickCallback onTimerTickCallback) {
        this.onTimerTickCallback = onTimerTickCallback;
    }

    public void setOnTimeFinishCallback(OnTimeFinishCallback onTimeFinishCallback) {
        this.onTimeFinishCallback = onTimeFinishCallback;
    }

    public void start(){
        super.start();
    }

    public void cancel(){
        isrunning = false;
    }

    @Override
    public void run() {
        super.run();
        if (sumTime < intervalTime) {
            throw new RuntimeException("Error:the summary time can't small than intervalTime");
        }
        while(isrunning) {
            sumTime = sumTime - intervalTime;
            if (sumTime == 0) {
                handler.sendEmptyMessage(ON_FINISHED);
                isrunning = false;
            } else {
                Log.d("timecount","tick:" + handler);
                handler.sendEmptyMessage(ON_TICK);
            }
            try {
                Thread.sleep(intervalTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private  Handler handler = new Handler(){
      public void handleMessage(Message msg) {
            switch (msg.what) {
                case ON_TICK:
                    if (onTimerTickCallback != null)onTimerTickCallback.onTick(sumTime);
                    break;
                case ON_FINISHED:
                    if (onTimeFinishCallback != null)onTimeFinishCallback.onFinish();
                    break;
            }
      }
    };
    /**
     *
     */
    public interface OnTimerTickCallback{
        void onTick(int time);

    }
   public interface OnTimeFinishCallback{
        void onFinish();
    }


    private static final int  ON_TICK = 0;
    private static final int ON_FINISHED = 1;
}
